UNION
λ°μ΄ν°λ² μ΄μ€μμ
UNION
μ λ κ° μ΄μμ SELECT
λ¬Έμ κ²°κ³Ό μ§ν©μ νλλ‘ κ²°ν©νλ λ° μ¬μ©λ©λλ€. UNION
μ μ€λ³΅λ νμ μ κ±°νκ³ κ²°κ³Ό μ§ν©μμ μ μΌν νλ§ λ°ννλ©°, UNION ALL
μ μ€λ³΅λ νλ λͺ¨λ ν¬ν¨ν©λλ€.Β
1. λ¬Έλ²
SELECT column1 FROM table1 WHERE condition1 UNION [ALL] SELECT column2 FROM table2 WHERE condition2;
column1
,column2
: λ°ννλ €λ μ΄μ μ΄λ¦μ λλ€.
table1
: λ°μ΄ν°λ₯Ό κ°μ Έμ¬ ν μ΄λΈμ μ΄λ¦μ λλ€.
WHERE
μ μ μ ν μ¬νμ λλ€. 쑰건μμ΄ λμ΄λλ€λ©΄, UNIONμ κ²°κ³Όμ ν¬ν¨λλ νμ νν°λ§ν©λλ€.
UNION
ν€μλλ λ κ° μ΄μμ SELECT λ¬Έμ κ²°κ³Όλ₯Ό ν©μΉλ λ° μ¬μ©λ©λλ€.
ALL
ν€μλλ μ€λ³΅λ νλ λͺ¨λ λ°νν©λλ€. μλ΅νλ©΄ μ€λ³΅λ νμ μ κ±°λ©λλ€.
Β
Β
μμ 1
SELECT name, age FROM students UNION SELECT name, age FROM teachers;
μ μμ λ
students
μ teachers
ν
μ΄λΈμμ name
κ³Ό age
μ΄μ μ ννκ³ , λ κ²°κ³Ό μ§ν©μ UNION
μΌλ‘ κ²°ν©ν©λλ€. μ΄λ₯Ό ν΅ν΄, νμκ³Ό κ΅μ¬μ μ΄λ¦κ³Ό λμ΄λ₯Ό λͺ¨λ λ°νν©λλ€. μ€λ³΅λ νμ μ κ±°λ©λλ€.Β
+--------+-----+ | name | age | +--------+-----+ | John | 20 | | Jane | 22 | | Peter | 25 | | Rachel | 30 | | Tom | 35 | | Mary | 40 | +--------+-----+
Β
μμ 2
SELECT name, age FROM students UNION ALL SELECT name, age FROM teachers;
μ μμ λ
students
μ teachers
ν
μ΄λΈμμ name
κ³Ό age
μ΄μ μ ννκ³ , λ κ²°κ³Ό μ§ν©μ UNION ALL
λ‘ κ²°ν©ν©λλ€. μ΄λ₯Ό ν΅ν΄, νμκ³Ό κ΅μ¬μ μ΄λ¦κ³Ό λμ΄λ₯Ό λͺ¨λ λ°νν©λλ€. μ€λ³΅λ νλ λͺ¨λ ν¬ν¨λ©λλ€.Β
+--------+-----+ | name | age | +--------+-----+ | John | 20 | | Jane | 22 | | Peter | 25 | | Rachel | 30 | | Tom | 35 | | Mary | 40 | | Jane | 30 | +--------+-----+
Β
Β
Β
Β
2. μ£Όμμ¬ν
UNION
κ³ΌUNION ALL
μ κ°κ° 2κ° μ΄μμSELECT
λ¬Έμ κ²°κ³Ό μ§ν©μ νλλ‘ κ²°ν©ν©λλ€. μ΄λ, κ°SELECT
λ¬Έμ μ΄ μμ λ°μ΄ν° μ νμ΄ λμΌν΄μΌ ν©λλ€.
UNION
κ³ΌUNION ALL
μ κ²°κ³Ό μ§ν©μ μ΄ μ΄λ¦μ 첫 λ²μ§ΈSELECT
λ¬Έμ μ΄ μ΄λ¦μΌλ‘ μ¬μ©ν©λλ€.
UNION
μ κ²°κ³Ό μ§ν©μμ μ€λ³΅λ νμ μ κ±°ν©λλ€.
UNION ALL
μ μ€λ³΅λ νλ λͺ¨λ ν¬ν¨ν©λλ€.
UNION
κ³ΌUNION ALL
μ μ±λ₯μ΄ μ’μ§ μμ μ μμΌλ―λ‘, νμν κ²½μ° λ체 λ°©λ²μ κ³ λ €ν΄μΌ ν©λλ€.
Β
Β
μ μ¬ν ν¨μ
MySQLμμλ
MINUS
λ INTERSECT
μ κ°μ μ§ν© μ°μ°μλ₯Ό μ§μνμ§ μμ΅λλ€. λμ , λ€λ₯Έ λ°©λ²μ μ¬μ©νμ¬ λμΌν κ²°κ³Όλ₯Ό μ»μ μ μμ΅λλ€.MINUS
λμ
MINUS
λ 첫 λ²μ§Έ SELECT
λ¬Έμλ ν¬ν¨λμ§λ§ λ λ²μ§Έ SELECT
λ¬Έμλ ν¬ν¨λμ§ μλ νμ λ°νν©λλ€.SELECT column1 FROM table1 WHERE condition1 EXCEPT SELECT column1 FROM table2 WHERE condition2;
μ μμ μμ
EXCEPT
λμ NOT IN
μ μ¬μ©νμ¬ λμΌν κ²°κ³Όλ₯Ό μ»μ μ μμ΅λλ€.SELECT column1 FROM table1 WHERE column1 NOT IN (SELECT column1 FROM table2 WHERE condition2);
Β
INTERSECT
λμ
INTERSECT
λ λ κ°μ SELECT
λ¬Έμ λͺ¨λ ν¬ν¨λλ νμ λ°νν©λλ€.SELECT column1 FROM table1 WHERE condition1 INTERSECT SELECT column1 FROM table2 WHERE condition2;
μ μμ μμ
INTERSECT
λμ INNER JOIN
μ μ¬μ©νμ¬ λμΌν κ²°κ³Όλ₯Ό μ»μ μ μμ΅λλ€.SELECT column1 FROM table1 INNER JOIN table2 ON table1.column1 = table2.column1 WHERE condition1 AND condition2;
μ΄ λ°©λ²μ μΌλ°μ μΌλ‘
INNER JOIN
μ΄ INTERSECT
λ³΄λ€ λ ν¨μ¨μ μ΄κΈ° λλ¬Έμ λ μ νΈλ©λλ€.